﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using System.Windows.Media.Imaging;


namespace imagehistogram
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
        }
        BitmapImage imagebitmap;
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog file = new OpenFileDialog();
            file.Filter = "file anh(*.jpg)|*.jpg";
           if (file.ShowDialog()==true)
           {
               Stream filestream = file.File.OpenRead();
               imagebitmap = new BitmapImage();
               imagebitmap.SetSource(filestream);
               image1.Source = imagebitmap;
           }
        }

       
        private void _scaleimage_Click(object sender, RoutedEventArgs e)
        {
            scaleimage.Source = MakeGray(image1);
        }
       
        
        private   WriteableBitmap MakeGray(Image img)
        {

            WriteableBitmap bitmap = new WriteableBitmap(img, null);

            for (int y = 0; y < bitmap.PixelHeight; y++)
            {

                for (int x = 0; x < bitmap.PixelWidth; x++)
                {

                    int pixelLocation = bitmap.PixelWidth * y + x;

                    int pixel = bitmap.Pixels[pixelLocation];

                    byte[] pixelBytes = BitConverter.GetBytes(pixel);

                    byte bwPixel = (byte)(.299 * pixelBytes[2] + .587 * pixelBytes[1] + .114 * pixelBytes[0]);

                    //pixelBytes[0] = bwPixel;

                    //pixelBytes[1] = bwPixel;

                    for (int k = 0; k < 3;k++ )
                    {
                        if (pixelBytes[k]>=127)
                        {
                            pixelBytes[k] = 255;
                        }
                        else
                        {
                            pixelBytes[k] = 0;
                        }
                    }
                    //pixelBytes[2] = bwPixel;

                    bitmap.Pixels[pixelLocation] = BitConverter.ToInt32(pixelBytes, 0);

                }
            }

            return bitmap;

        }

        
    }
}
